#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2025/4/24 2:26
# @Author   : MingTai
# @File     : video_frames.py

import cv2
import os

from app.utils.time_util.time_handle import get_second_time_str
from app.utils.video_utile import video_path_url, video_path_url2


def extract_frames(video_path, output_folder):
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)

    # 获取视频的总帧数
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    # 确保输出文件夹存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 计算每多少帧抽取一帧,18备用
    interval = total_frames // 18

    saved_count = 0
    frame_count = 0

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        if frame_count % interval == 0 and saved_count < 18:
            frame_filename = os.path.join(output_folder, f"image{saved_count + 1}.jpg")
            print(f"保存image{saved_count + 1}.jpg")
            cv2.imwrite(frame_filename, frame)
            saved_count += 1

        frame_count += 1

    cap.release()
    print(f"Total saved frames: {saved_count}")


# 把mp4视频平均抽18张照片
if __name__ == '__main__':
    # 参数设置
    video_path1 = video_path_url2  # 替换为你的视频文件路径

    output_folder1 = f'image_{get_second_time_str()}'  # 替换为你想要保存帧的文件夹
    print(f'video_path1: {output_folder1}')

    # 抽取帧
    extract_frames(video_path1, output_folder1)
